package databasePackage;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

public class MySqlDatabase {
	// databaseData bevat tabelnamen, kolomnamen en kolomtypes.
	// tabelnamen op [n][0][0]
	// kolomnamen op [n][0 + (n+1)][0]
	// kolomtype op [n][0 + (n+1)][1]
	private String[][][] databaseData;
	private DatabaseConnectionController dbController;
	private Connection connection;
	private int aantalKolommen;

	public MySqlDatabase(DatabaseConnectionController dbController) {
		this.dbController = dbController;
		initializeDatabaseData();
	}

	// Bepaal de grootte van de dimensie van de array databaseData
	private void initializeDatabaseData() {
		int numberOfTables = 0, maxColumns = 0;
		aantalKolommen = 0;
		try {
			connection = dbController.openMySqlConnection();
			DatabaseMetaData dbm = connection.getMetaData();
			String[] types = { "TABLE" };
			ResultSet rs = dbm.getTables(null, null, "%", types);
			for (; rs.next(); numberOfTables++) {
				String tableName = rs.getString("TABLE_NAME");
				String query = "SELECT * FROM " + tableName;
				ResultSet rsColumns = dbController.doQuery(query);
				ResultSetMetaData rsmdColumns = rsColumns.getMetaData();
				int rowCount = rsmdColumns.getColumnCount();
				maxColumns = (rowCount > maxColumns) ? rowCount : maxColumns;
				aantalKolommen += rowCount;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		databaseData = new String[numberOfTables][maxColumns + 1][2];
		dbController.closeConnection();
	}

	public void importDatabaseData() {
		try {
			connection = dbController.openMySqlConnection();
			DatabaseMetaData dbm = connection.getMetaData();
			String[] types = { "TABLE" };
			ResultSet rs = dbm.getTables(null, null, "%", types);
			for (int i = 0; rs.next(); i++) {
				String tableName = rs.getString("TABLE_NAME");
				String query = "SELECT * FROM " + tableName;
				ResultSet rsColumns = dbController.doQuery(query);
				ResultSetMetaData rsmdColumns = rsColumns.getMetaData();
				int rowCount = rsmdColumns.getColumnCount();
				// tabelnamen op databaseData[i][0][0]
				databaseData[i][0][0] = tableName;
				for (int j = 0; j < rowCount; j++) {
					// kolomnamen op [i][j+(n+1)][0]
					// kolomtypes op [i]j+(n+1)][1]
					databaseData[i][j + 1][0] = rsmdColumns.getColumnName(j + 1);
					databaseData[i][j + 1][1] = rsmdColumns.getColumnTypeName(j + 1);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		dbController.closeConnection();
	}

	public String[][][] getDatabaseData() {
		return databaseData;
	}

	public int getAantalKolommen() {
		return aantalKolommen;
	}
}